import Api from '@/services/api.js'
import commonApi from '@/services/api.js'
import store from '@/store/store';
//const ODB_BASE = 'http://localhost:8080/jeecg-boot/front';
const ODB_BASE = 'https://front.shencezixun.cn/api/front';
let app = getApp();
class Serv {
  constructor(props) {
    this.timer = null;
    this.$store = store;
    this.NODE_BASE = ODB_BASE;
  }
  //接口请求
  request = async ({
    url,
    data = {},
    method = 'GET',
    loading = true,
    header = {
      // 'Content-Type': 'application/json'
    },
  }) => {
    data = {
      //todo 如果有其他特殊处理或固定参数 写在此处
      ...data
    }
    header = {
      //todo 如果有其他特殊处理或固定请求头参数 写在此处
      'utoken': this.$store.state.privacyData.token || '',
      ...header,
    }
    return this.httpRequest({
      url,
      header,
      method,
      data,
      loading
    });
  }
  //发起网络请求
  //如果有http 直接使用
  httpRequest({
    url,
    header,
    method,
    data,
    loading = true
  }) {
    let thirdApi = this.isThirdApi(url);
    loading && this.showLoading()
    return new Promise((resolve, reject) => {
      uni.request({
        url: thirdApi ? url : `${ODB_BASE}${url}`,
        data,
        method,
        header,
        timeout: 15000,
        success: (res) => {
          loading && this.hideLoading()
          if (res.statusCode == 200) {
            //如果是三方api 直接返回结果
            if (thirdApi) {
              resolve(res.data)
              return
            }
            //接口请求成功code 判断
            if (res.data.code != 200) {
              uni.showToast({
                title: res.errMsg != 'request:ok' ? res.errMsg : res.data.message || '接口请求错误',
                icon: 'none'
              });
              reject(res);
            } else {
              resolve(res.data);
            }
          } else {
            reject(res);
          }
        },
        fail: (err) => {
          loading && this.hideLoading();
          reject(err)
        }
      })
    })
  }

  // 是否是三方api 三方api 直接使用接口地址
  isThirdApi(url) {
    console.log('url==============>', url);
    return url.includes('http');
  }

  //获取用户信息
  async getUserInfo(desc = '获取用户报名基础信息') {
    uni.showLoading({
      title: '加载中...',
      icon: 'none'
    })
    // getUserProfile
    return new Promise((resolve, reject) => {
      uni.getUserInfo({
        desc,
        success: (res) => {
          const {
            encryptedData
          } = res;
          if (typeof (encryptedData) != 'object') {
            const {
              nickName,
              avatarUrl
            } = res.userInfo;
            this.$store.commit(
              'setStore', {
              privacyData: {
                nickName,
                avatarUrl
              }
            }
            )
          }
          resolve(res);
        },
        fail: (err) => {
          reject(err);
        },
        complete: () => {
          uni.hideLoading();
        }
      })
    })
  }

  //渠道授权登录
  async getAuthCode(payload = {}) {
    return new Promise((resolve, reject) => {
      uni.login({
        success: async (res) => {
          if (res.errMsg == 'login:ok') {
            resolve(res);
          } else {
            reject(res);
          }
        }
      })
    })
  }



  //登录
  async login(args) {
    const { inviterId = '', inviteType = 'other' } = args || {};
    const { code } = await this.getAuthCode();
    const ret = await this.request({
      url: Api.decodeUserInfo,
      method: 'POST',
      data: {
        code,
        inviterId,
        inviteType
      }
    })
    if (ret.code == 200) {
      await this.savePrivacyData({ ...ret.result })
    }
  }

  // 存储用户数据
  async savePrivacyData(privacy) {
    await this.$store.commit('setStore', {
      privacyData: {
        ...privacy
      }
    })
    uni.setStorageSync('privacyData', {
      ...privacy
    })

  }

  // 更新个人数据
  async updatePrivacyData(data) {
    // 深拷贝一次
    const privacy = { ...this.$store.state.privacyData };
    await this.$store.commit('setStore', {
      privacyData: Object.assign(privacy, data)
    })
    uni.setStorageSync('privacyData', Object.assign(privacy, data));
  }

  // 根据邀请用户id绑定用户
  async userBindByInviterId(params) {
    const { inviterId, userId } = this.$store.state.privacyData;
    // 如果有邀请人id 就不绑定了
    if (inviterId || inviterId == userId) return;
    const { code } = await this.request({
      url: Api.userBindByInviterId,
      method: 'POST',
      data: { 
        inviterId: params.inviterId,
        userId 
      }
    });
    // 绑定成功 就存起来
    if (code === 200) {
      this.$store.commit('setStore', {
        privacyData: {
          inviterId: params.inviterId
        }
      })
    }
  }

  //显示加载状态
  showLoading() {
    //处理toast和loading冲突，不显示，挂载变量到全局globalData
    // if (xxxx) {
    //   return
    // }
    clearTimeout(this.timer)

    uni.showLoading({
      title: '加载中',
      mask: true
    })
  }

  //隐藏加载状态
  hideLoading() {
    clearTimeout(this.timer)
    this.timer = setTimeout(() => {
      uni.hideLoading()
    }, 300);
  }

  // 获取支付信息
  async getPayInfo(params) {
    console.log('支付参数------------->', params);
    if (!params?.vipId) {
      return uni.showToast({
        title: '支付参数错误',
        icon: 'none'
      })
    }
    const {
      code,
      result
    } = await this.request({
      url: Api.getWxPayInfo,
      method: 'POST',
      data: params
    })
    if (code === 200) {
      return this.requestPayment(result);
    } else {
      uni.showToast({
        title: '支付请求失败',
        icon: 'none'
      })
      return null;
    }
  }

  // 请求支付
  requestPayment(params) {
    return new Promise((resolve, reject) => {
      uni.requestPayment({
        provider: 'wxpay',
        appid: params?.appId,
        nonceStr: params?.nonceStr,
        package: params?.package,
        timeStamp: params?.timeStamp,
        signType: params?.signType,
        paySign: params?.paySign,
        success: res => {
          resolve(res);
        },
        fail: err => {
          reject(err)
        },
        complete: com => { }
      })
    })
  }

  // 获取存储的用户数据
  getPrivacyData() {
    return uni.getStorageSync('privacyData') || {};
  }
  /**
   * 对在App.js阶段无法获取得APP进行绑定外部传入app
   */
  setApp(appData) {
    if (!app) {
      app = appData;
    }
    return this;
  }

  // 获取位置信息
  async getLocation(type) {
    return new Promise((resolve, reject) => {
      uni.getLocation({
        type: 'wgs84',
        success: async (res) => {
          if (type == 'onLaunch') {
            this.$store.commit('setStore', {
              location: {
                lat_x: res.latitude, // 不做重新赋值 不做改变 始终保持用户定位的经纬度
                lng_y: res.longitude, // 不做重新赋值 不做改变 始终保持用户定位的地址
                lat: res.latitude,
                lng: res.longitude,
              }
            })
            // 定位完成之后要进行逆编码
            // this.getCityListByLatlng();
          } else {
            resolve(res);
          }
        },
        fail: res => {
          console.log('定位失败==>', res);
        }
      })
    })
  }

  async getCityListByLatlng() {
    const {
      lat_x,
      lng_y
    } = this.$store.state.location;
    const {
      suc,
      result
    } = await this.request({
      url: Api.getCityByLatlng,
      method: 'GET',
      data: {
        lat: lat_x,
        lng: lng_y,
      }
    });
    if (suc) {
      this.$store.commit('setStore', {
        location: {
          city: {
            name: result.cname,
            id: result.cid,
            adCode: result.ccode
          },
          province: {
            name: result.pname,
            id: result.pid
          }
        }
      })
    }
  }
  // 地图逆编码
  async mapReeo() {
    const {
      infocode,
      regeocode
    } = await this.request({
      url: Api.regeo,
      method: 'GET',
      data: {
        key: '3dfaeb3923a8c44ebe45ce2574f3f92e',
        location: `${location.lng_y},${location.lat_x}`
      },
    })
    // 10000表示地图api请求正常
    if (infocode == 10000) { }
  }


  // 获取分销比例
  async getCommissionRateByAgentId() {
    const {
      suc,
      result
    } = await this.request({
      url: Api.getCommissionRateByAgentId,
      data: {
        userId: this.$store.state.privacyData.userId
      }
    })
    if (suc) {
      this.$store.commit('setStore', {
        commissionRate: result / 100 // 按百分比
      })
    }
  }

  // 获取企业列表
  getEnterpriseList(type) {
    return new Promise(async (resolve, reject) => {
      const { code, result } = await this.request({
        url: Api.getEnterprisesList,
      })
      if (code == 200) {
        result.forEach(i => {
          i.logoUrl = JSON.parse(i?.extinfor || '{}').logoUrl;
        })
        if (type == 'all') {
          resolve(result)
        }else {
          const list = result.filter(i => i.auditStats == 1);
          if (type == 'init' && list.length > 0) {
            this.$store.commit('setStore', {
              companyInfo: {
                enterpriseId: list[0].id,
                companyName: list[0].title,
                logoUrl: list[0].logoUrl
              }
            })
          }
          resolve(list);
        }
      }
    })
  }

  // 根据企业id获取企业部门
  getEnterpriseDepartments(arg) {
    const showLoading = arg?.showLoading || true;
    const enterpriseId = arg?.enterpriseId || this.$store.state.companyInfo.enterpriseId;
    return new Promise(async (resolve, reject) => {
      const ret = await this.request({
        url: Api.getEnterpriseDepartments,
        data: { enterpriseId },
        showLoading
      })
      if (ret.code == 200) {
        let departments = ret.result.map(i => {
          // 组装成弹窗封装好的数据字段
          i.val = i.name;
          i.key = i.id;
          let jobIds = i?.jobIds ? i?.jobIds.split(',') : [];
          let jobTxts = i?.jobIds_dictText ? i?.jobIds_dictText.split(',') : [];
          // 组装部门的岗位数据
          i.children = jobIds.reduce((prev, next, idx) => {
            prev.push({ 
              key: next, 
              val: jobTxts[idx],
              id: next,
              name: jobTxts[idx],
            })
            return prev;
          }, [])
          return i;
        });
        resolve(departments)
      }
    })

  }

  // 当前页面路由
  currentPageRoute() {
    let pages = getCurrentPages();
    let currentPage = pages[pages.length - 1];
    return currentPage.route;
  }

  /**
   * 校验是否登录
   * @param {是否校验} isCheck 
   * @returns 
   */
  checkAuthLogin(isCheck = false) {
    const { phone, avatarUrl } = this.$store.state.privacyData;
    if (isCheck && (!phone || !avatarUrl)) {
      uni.showModal({
        title: '提示',
        content: '当前未登录，请先登录',
        confirmText: '去登录',
        confirmColor: '#0165FC',
        success: (res => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/login/index'
            })
          }
        })
      })
      return true;
    }
    return false;
  }

  /**
   * 返回或者重定向到目标页
   * 目标页默认首页
   * @param {重定向页面地址} redirectPage 
   */
  backTargetPage(pageUrl = '/pages/home/index', type = 'reLaunch') {
    const pages = getCurrentPages();
    // 获取上一个页面的路由
    const prePage = pages[pages.length - 2]
    prePage
      ?
      uni.navigateBack()
      :
      uni[type]({
        url: pageUrl
      })
  }
}

export default new Serv();

// const _serv = new Serv();
// module.exports = {
//   request: _serv.request,
//   serv: _serv
// }